<template>
  <view class="login-container">
    <view class="login-header">
      <text class="title">手机号登录</text>
    </view>
    
    <view class="form-item">
      <text class="label">手机号</text>
      <input 
        class="input" 
        type="number" 
        v-model="phone" 
        placeholder="请输入手机号" 
        maxlength="13"
      />
    </view>
    
    <view class="form-item">
      <text class="label">验证码</text>
      <input 
        class="input" 
        type="number" 
        v-model="code" 
        placeholder="请填写验证码" 
        maxlength="6"
      />
      <button 
        class="code-btn" 
        :disabled="countdown > 0" 
        @click="getCode"
      >
        {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
      </button>
    </view>
    
    <button class="login-btn" @click="handleLogin">登录</button>
    
    <!-- 位置权限请求弹窗 -->
    <view class="location-modal" v-if="showLocationModal">
      <view class="modal-content">
        <text class="modal-title">获取你的位置信息</text>
        <text class="modal-desc">你的位置信息将用于获取你附近的站点</text>
        <view class="modal-btns">
          <button class="modal-btn reject" @click="handleReject">拒绝</button>
          <button class="modal-btn allow" @click="handleAllow">允许</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref,onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const phone = ref('')
const code = ref('')
const countdown = ref(0)
const showLocationModal = ref(false)
let timer = null

// 获取验证码
const getCode = () => {
	
	console.log("111")
	
  if (!phone.value) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  
  console.log(phone.value)

  uni.showLoading({ title: '发送中...' })

  uni.request({
    url: 'http://localhost:8080/auth/sms/sendSms',
    method: 'POST',
    data: {
      phoneNumber: ["+86" + phone.value] 
    },
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        uni.hideLoading()
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })

        // 开始倒计时
        countdown.value = 60
        timer = setInterval(() => {
          if (countdown.value <= 0) {
            clearInterval(timer)
            return
          }
          countdown.value--
        }, 1000)
      } else {
        uni.hideLoading()
        uni.showToast({
          title: res.data.message || '验证码发送失败',
          icon: 'none'
        })
      }
    },
    fail: () => {
      uni.hideLoading()
      uni.showToast({
        title: '网络异常，请稍后再试',
        icon: 'none'
      })
    }
  })
}


// 处理登录
// 登录成功后
const handleLogin = async () => {
  if (!phone.value) {
    uni.showToast({ title: '请输入手机号', icon: 'none' })
    return
  }

  if (!code.value) {
    uni.showToast({ title: '请输入验证码', icon: 'none' })
    return
  }

  uni.showLoading({ title: '登录中...' })

  uni.request({
    url: 'http://localhost:8080/auth/wxLogin',
    method: 'POST',
    header: {
      'content-type': 'application/json'
    },
    data: {
      phone: "+86" + phone.value,
      code: code.value
    },
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        const token = res.data.data.token
        const userInfo = res.data.data.sysUser

        
        const app = getApp(); // 获取全局应用实例
        app.globalData.userInfo = userInfo; // 赋值用户信息
        app.globalData.token = token; // 赋值 token

        uni.hideLoading()
		
		showLocationModal.value = true
        

		console.log("userInfo:",app.globalData.userInfo)
		console.log("token:",app.globalData.token)
        
      } else {
        uni.hideLoading()
        uni.showToast({ title: res.data.msg || '登录失败', icon: 'none' })
      }
    },
    fail: () => {
      uni.hideLoading()
      uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' })
    }
  })
}




// 处理拒绝位置权限
const handleReject = () => {
  showLocationModal.value = false
  navigateToHome()
}

// 处理允许位置权限
const handleAllow = () => {
  // 获取位置信息
  uni.getLocation({
    type: 'gcj02',
    success: () => {
      uni.showToast({
        title: '位置获取成功',
        icon: 'success'
      })
	  uni.showToast({ title: '登录成功', icon: 'success' })

      // 延迟 1 秒跳转
      setTimeout(() => {
        navigateToHome();
      }, 1000);
    },
    fail: () => {
      uni.showToast({
        title: '位置获取失败',
        icon: 'none'
      })
    },
    complete: () => {
      showLocationModal.value = false

      // 延迟 1 秒跳转
      setTimeout(() => {
        navigateToHome();
      }, 1000);
    }
  })
}

// 跳转到首页
const navigateToHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

// 清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

<style lang="scss">
.login-container {
  padding: 60rpx 50rpx;
  
  .login-header {
    margin-bottom: 80rpx;
    
    .title {
      font-size: 48rpx;
      font-weight: bold;
    }
  }
  
.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 40rpx;
  position: relative;
  /* 新增：为右侧按钮预留空间 */
  padding-right: 140rpx; /* 根据按钮宽度调整，确保按钮不被挤压 */
  
  .label {
    width: 120rpx;
    font-size: 32rpx;
    color: #333;
  }
  
  .input {
    flex: 1;
    font-size: 32rpx;
    height: 60rpx;
    /* 新增：限制输入框最大宽度，避免挤压按钮 */
    max-width: calc(100% - 120rpx); /* 减去label的宽度，防止溢出 */
  }
  
  .code-btn {
    position: absolute;
    right: 0; /* 保持右对齐 */
    background: none;
    border: none;
    font-size: 28rpx;
    color: #2196F3;
    padding: 10rpx 20rpx; /* 增加内边距，扩大点击区域 */
    width: 220rpx; /* 固定按钮宽度，避免文字换行导致宽度变化 */
    text-align: center; /* 文字居中 */
    
    &::after {
      border: none;
    }
    
    &[disabled] {
      color: #999;
    }
  }
}
  
  .login-btn {
    margin-top: 80rpx;
    background-color: #2196F3;
    color: #fff;
    height: 90rpx;
    line-height: 90rpx;
    border-radius: 45rpx;
    font-size: 36rpx;
  }
}

.location-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  
  .modal-content {
    width: 80%;
    background-color: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    text-align: center;
    
    .modal-title {
      font-size: 36rpx;
      font-weight: bold;
      display: block;
      margin-bottom: 20rpx;
    }
    
    .modal-desc {
      font-size: 28rpx;
      color: #666;
      display: block;
      margin-bottom: 40rpx;
    }
    
    .modal-btns {
      display: flex;
      justify-content: space-between;
      
      .modal-btn {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 32rpx;
        border-radius: 40rpx;
        
        &.reject {
          background-color: #f5f5f5;
          color: #333;
          margin-right: 20rpx;
        }
        
        &.allow {
          background-color: #2196F3;
          color: #fff;
        }
      }
    }
  }
}
</style>